Immediately Executing Function Demo

The key aspect of this demo is that the utilization of an immediately executing function in JavaScript generates a fresh variable scope, which distinguishes it from if, else, and while. The code presented below exemplifies this fact.

1
2
3
4
5
6
7
8
9
10
11
12
var foo = 123

if (1) {
var foo = 456
}

(_ => {
var foo = 123
})()

console.log(foo)

Output:

456

Notice how the function does not reset the value of variable foo? Now that’s something to be mindful of!